package com.vv.tools.common.util;

import jakarta.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;

/**
 * @author wen.li
 */
@Slf4j
public class IPUtil {

    private static final String UNKNOWN_STR = "unknown";

    private IPUtil() {
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = null;

        try {
            String xIp = request.getHeader("X-Real-IP");
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isNotEmpty(ip) && !UNKNOWN_STR.equalsIgnoreCase(ip)) {
                int index = ip.indexOf(",");
                if (index != -1) {
                    return ip.substring(0, index);
                }

                return ip;
            }

            ip = xIp;
            if (StringUtils.isEmpty(ip) || UNKNOWN_STR.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }

            if (StringUtils.isEmpty(ip) || ip.isEmpty() || UNKNOWN_STR.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }

            if (StringUtils.isEmpty(ip) || UNKNOWN_STR.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }

            if (StringUtils.isEmpty(ip) || UNKNOWN_STR.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }

            if (StringUtils.isEmpty(ip) || UNKNOWN_STR.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception var4) {
            log.error("{code:{},msg:[{}]}", "GET_IP_FROM_REQUEST", var4.getMessage(), var4);
        }

        return ip;
    }

}
